<template>
  <div>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="3" >
          <el-button type="primary" icon="el-icon-plus"  @click="add_user">添加用户</el-button>
        </el-col>
        <el-col :span="4">
          <el-input v-model="listData.search_info" @keyup.enter.native="search" placeholder="请输入网名或账号">
            <i class="el-icon-search" slot="suffix" @click="search" style="line-height: 40px"></i>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="listData.roleValue" @change="getUserList" clearable placeholder="请选择角色">
            <el-option
                v-for="item in roleoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="resetUser" style="margin-left: -130px;">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格显示区 -->
    <el-card class="table-card">
      <el-table :data="currentTableData" border style="width: 100%">
        <el-table-column prop="icon" label="头像" width="180">
          <template slot-scope="scope">
            <img :src="scope.row.icon" style="width: 50px;height: 50px;border-radius: 50%">
          </template>
        </el-table-column>
        <el-table-column prop="u_name" label="账号" width="180"></el-table-column>
        <el-table-column prop="u_pwd" label="密码" width="180"></el-table-column>
        <el-table-column prop="u_realname" label="网名" width="180"></el-table-column>
        <el-table-column prop="u_redgt" label="注册时间" width="180" :formatter="dataformatter"></el-table-column>
        <el-table-column prop="u_role" label="角色"></el-table-column>
        <el-table-column prop="u_mark" label="备注" width="180"></el-table-column>
        <el-table-column prop="u_phone" label="电话" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.u_phone">{{ scope.row.u_phone }}</span>
            <span v-else style="color: #d9d9d9">暂无数据</span>
          </template>
        </el-table-column>
        <el-table-column prop="u_address" label="地址" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.u_address">{{ scope.row.u_address }}</span>
            <span v-else style="color: #d9d9d9">暂无数据</span>
          </template>
        </el-table-column>
        <!-- 表格的操作栏 -->
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="update_user(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
            <el-button @click="delete_user(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="this.listData.currentPage"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="this.listData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredTableData.length">
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户对话框-->
    <el-dialog
        @close="closeDialog"
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-form :model="user_form" :rules="rules" ref="user_form">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="u_name">
          <el-input  v-model="user_form.u_name" :disabled="isdisable" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="网名" :label-width="formLabelWidth" prop="u_realname">
          <el-input v-model="user_form.u_realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="u_pwd">
          <el-input v-model="user_form.u_pwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认" :label-width="formLabelWidth"  prop="ru_pwd">
          <el-input v-model="user_form.ru_pwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth"  prop="u_role">
          <el-select v-model="user_form.u_role" placeholder="请选择角色类型">
            <el-option label="0" value="0"></el-option>
            <el-option label="1" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth"  prop="u_mark">
          <el-select v-model="user_form.u_mark" placeholder="请选择角色">
            <el-option  value="超级管理员"></el-option>
            <el-option  value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth"  prop="u_phone">
          <el-input v-model="user_form.u_phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth"  prop="u_address">
          <el-input v-model="user_form.u_address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth" prop="icon">
          <!--        上传控件-->
          <el-upload
              class="avatar-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="change_icon"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="subForm">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    // 自定义账号验证规则
    var validateAccount = async (rule, value, callback) => {
      //添加用户做校验，修改用户不做校验
      if (this.dialogTitle=="添加用户"){
        // 判断账号是否重复
        const {data:res} = await this.$axios.get("user/checkUname",{params:{u_name:this.user_form.u_name}})
        if (res.data==null){
          callback();
        }else if (value === res.data.u_name) {
          callback(new Error('账号已存在'));
        } else {
          callback();
        }
      }
    };
    //自定义校验规则，验证密码是否一致
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.user_form.ru_pwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      roleoptions: [{
        value: '0',
        label: '超级管理员'
      }, {
        value: '1',
        label: '普通用户'
      }],
      isdisable:false,//账号框是否禁用
      dialogTitle:"",
      formData:new FormData(),//表单类型的数据对象，可以包含文件
      imageUrl:'',//上传头像的地址
      formLabelWidth: '120px',
      rules: {
        u_name:[
          {  required: true, message: '请输入账号', trigger: 'blur'},
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
          {validator:validateAccount,trigger: 'change'}
        ],
        u_realname:[
          {required: true, message: '请输入网名', trigger: 'blur'},
        ],
        u_pwd:[
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
        ru_pwd:[
          {required: true, message: '请输入再次密码', trigger: 'blur'},
          {validator:validatePass,trigger: 'blur'}
        ],
        u_role:[
          {required: true, message: '请选择角色', trigger: 'blur'},
        ],
      },
      user_form:{
        u_id:"",
        u_name:"",
        u_pwd:"",
        ru_pwd:"",
        u_realname:"",
        u_redgt:"",
        u_role:"",
        u_mark:"",
        u_phone:"",
        u_address:"",
        icon:"",
      },
      dialogVisible: false,
      searchQuery: '',
      tableData: [],
      listData:{
        roleValue: "",
        search_info:"",//搜索
        currentPage: 1, // 当前页码
        pageSize: 5,   // 每页显示条数
        total:0
      },

    };
  },
  computed: {
    filteredTableData() {
      if (!this.searchQuery) return this.tableData;
      return this.tableData.filter(item => {
        return Object.values(item).some(val => val.toString().includes(this.searchQuery));
      });
    },
    currentTableData() {
      const start = (this.listData.currentPage - 1) * this.listData.pageSize;
      const end = start + this.listData.pageSize;
      return this.filteredTableData.slice(start, end);
    }
  },
  methods: {
    resetUser(){
      this.listData={
        search_info:"",//搜索
        currentPage:1,
        pageSize:5,
        total:0
      }
      this.getUserList()
    },
    //头像上传成功
    change_icon(file) {
      //图片预览图访问地址
      this.imageUrl = URL.createObjectURL(file.raw);
      this.formData.delete("file")
      if (this.imageUrl){
        this.formData.append("file",file.raw)
        console.log(this.formData)
      }
    },
    //头像上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 10;
      console.log(file.type);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 获取用户数据
    async getUserList() {
        const { data: res } = await this.$axios.get("/user/listUser");
        console.log(res)
        this.tableData = res.data;
    },
    search() {
      this.getUserList()
    },
    handleSizeChange(val) {
      this.listData.pageSize = val;
      this.listData.currentPage = 1; // 重置到第一页
    },
    handleCurrentChange(val) {
      this.listData.currentPage = val;
    },
    dataformatter(row){
      if (row.u_redgt){
        let date = new Date(row.u_redgt);
        return  date.toLocaleString()
      }
    },
    //关闭对话框
    closeDialog(){
      this.$refs.user_form.resetFields();//重置表单
      this.imageUrl=""//清空表单
      this.formData = new FormData();//重置formData对象的数据
      this.user_form={//重置user_form对象
        u_id:"",
        u_name:"",
        u_pwd:"",
        ru_pwd:"",
        u_realname:"",
        u_redgt:"",
        u_role:"",
        u_mark:"",
        u_phone:"",
        u_address:"",
        icon:"",
      }
      this.getUserList()
    },
    // 提交表单
    subForm(){
      this.$refs.user_form.validate(async (valid) => {
        if (valid){
          //把user_form中的数据封装到formData

          if (this.user_form.u_redgt){
            this.user_form.u_redgt = new Date(this.user_form.u_redgt)
          }else {
            this.user_form.u_redgt = new Date()
          }
          for (let key in this.user_form){
            this.formData.append(key,this.user_form[key])
          }
          //请求后端添加用户接口
          const {data:res} = await this.$axios.post("/user/addOrUpdate",this.formData)
          console.log(res)
          if (res.data){
            this.$message.success("操作成功")
            this.dialogVisible = false
            await this.getUserList()
          }else {
            this.$message.error("添加失败")
            return false;
          }
        }
      })
    },
    //添加用户
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    //删除用户
    delete_user(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$axios.get("/user/deleteById", {params: {u_id:row.u_id}})
        if (res.data){
          this.$message.success('删除成功')
          await this.getUserList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    update_user(row){
      console.log(this.formData)
      this.imageUrl=row.icon
      this.user_form = row
      this.user_form.ru_pwd=row.u_pwd
      this.dialogVisible = true
      this.dialogTitle="修改用户信息"
      this.isdisable=true
    },
    //添加用户
    add_user(){
      this.dialogVisible = true
      this.dialogTitle="添加用户"
      this.isdisable=false
    }
  }
};
</script>

<style scoped>
.custom-card {
  padding: 20px;
}
.table-card {
  padding: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>